from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse
from django.contrib.auth.models import User,ContentType,Permission,Group
from django.contrib.auth import authenticate
from .forms import LoginForm
from django.views.generic import View
# from .models import Person
# Create your views here.
from django.contrib.auth import login,logout
from django.contrib.auth.decorators import login_required,permission_required
from .models import User,Article



@login_required(login_url='/login/')
def index(request):
    #user = User.objects.create_user(username='kangbazi',password='91wangfan',email="91wangfan@qq.com")
    # user = User.objects.get(pk=1)
    # user.set_password("91daxiong")
    # user.save()

    # username = 'kangbazi'
    # password = '91daxiong'
    # user = authenticate(request,username=username,password=password)
    # if user:
    #     print(user)
    # else:
    #     print("用户名或者密码错误")
    # user = User.objects.create_superuser(username='91wangfan',password='1301231',email="123@qq.com")
    # user.save()
    # user = User.objects.create_user(telephone='17777777777',username='123qweasd',password="123123123!")
    # user.save()
    # user = User.objects.create_user(telephone='17777777777', username='91wangfan', password="123456")
    # user.save()
    # user = User.objects.create_user(telephone='18888888888',username="kangbazi",password='123123',email="wangfan@91.com")
    # user.save()
    return render(request,'index.html')


#一对一外键 扩展
def one_view(request):
    # user = User.objects.create_user(username="jiangjie",email="jiejie@qq.com",password="123456")
    user = User.objects.create_user(username="jiangjie1",email="jiejie1@qq.com",password="123456")
    user.extension.telephone = '18999999999'
    user.save()

    return HttpResponse("one to one ")





#代理扩展
def proxy_view(request):
    # blacklist = Person.get_blacklist()
    # for bla in blacklist:
    #     print(bla.username)
    return HttpResponse("PROXY")

# 验证用户的密码
def my_authenticate(username,password):
    user = User.objects.filter(username=username).first()
    if user:
        is_correct = user.check_password(password)
        if is_correct:
            return user
        else:
            return None
    else:
        return None
#手机号验证   一对一扩展模型
def my_authenticate_extension(telephone,password):
    user = User.objects.filter(extension__telephone=telephone).first()
    if user:
        is_correct = user.check_password(password)
        if is_correct:
            return user
        else:
            return None
    else:
        return None

def test_view(request):
    username = request.GET.get('username')
    password = request.GET.get('password')
    user = my_authenticate(username,password)
    if user:
        print("%s验证成功" % user.username)
    else:
        print("验证失败")
    return HttpResponse("ojok")

def test_extension_view(request):
    username = request.GET.get('telephone')
    password = request.GET.get('password')
    user = my_authenticate_extension(username,password)
    if user:
        print("%s验证成功" % user.username)
    else:
        print("验证失败")
    return HttpResponse("ojok")

def inherite_view(request):
    telephone='18888888888'
    username='91wangfan'
    password='123abcaa'
    # user = User.objects.create_user(telephone=telephone,username=username,password=password)
    # print(user.username)
    user = authenticate(request,username='18888888888',password='123abcaa')
    #因为我们重写了User模型  并且USERNAME_FIELD = 'telephone' 原来是以username作为唯一的验证
    #现在 是以手机号作为唯一的验证  但是还是username
    if user:
        print(user.telephone)
        print("success")
    else:
        print("fail")
    return HttpResponse("KUOZHAN")
#User模型中 有login方法  自己写的时候不要再写一遍了
def my_login(request):
    if request.method == 'GET':
        return render(request,'login.html')
    else:
        forms = LoginForm(request.POST)
        if forms.is_valid():
            telephone = forms.cleaned_data.get('telephone')
            password = forms.cleaned_data.get('password')
            remember = forms.cleaned_data.get('remember')
            user = authenticate(request,username=telephone,password=password)
            if user and user.is_active:
                login(request,user)
                if remember:
                    request.session.set_expiry(None)
                else:
                    request.session.set_expiry(0)
                next_url = request.GET.get('next')
                if next_url:
                    return redirect(next_url)
                else:
                    return HttpResponse("登录成功")
            else:
                return HttpResponse("手机号或者密码错误")

        else:
            print(forms.errors)
            return redirect(reverse('login'))

def my_logout(request):
    logout(request)
    return redirect(reverse('index'))


@login_required(login_url='/login/')
def profile(request):
    return HttpResponse("只有登录以后才可以看到我")
#代码给模型添加权限
def add_permission(request):
    #首先获取模型的id 也就是content_type

    content_type = ContentType.objects.get_for_model(Article)
    permission = Permission.objects.create(codename="balck_article",name="拉黑文章",content_type=content_type)
    return  HttpResponse("权限添加成功")

def operate_permission(request):
    #给哪个用户添加权限 先要获取这个用户
    user = User.objects.first()
    #让用户对什么进行操作  比如操作文章  那就获取文章的content_type
    content_type= ContentType.objects.get_for_model(Article)
    #获取文章的所有的权限  默认增删改 我们自己也可以添加权限
    permissions = Permission.objects.filter(content_type=content_type)
    for permission in permissions:
        print(permission)
    #把所有的权限给用户添加进去
    # user.user_permissions.set(permissions)
    # user.save() 记住保存
    # user.user_permissions.clear() 清除所有的权限
    # user.save() 记住保存
    user.user_permissions.set(permissions)
    user.save()
    # user.user_permissions.remove(permissions[3])
    # user.save()
    # user.user_permissions.remove(*permissions)
    # user.save()
    # if user.has_perms(['front.change_article']):
    #     print("拥有修改文章的权限")
    # else:
    #     print("没有修改文章的权限")
    print(user.get_all_permissions())
    return HttpResponse("操作权限的方法")

#raise_exception=403如果没有登录 或者没有权限 通通给你报403错误
#@permission_required(['front.add_article','front.view_article'],login_url='/login/',raise_exception=403)
@permission_required('front.view_article',login_url='/login/')
def add_article(request):
    # #1.判断用户是否登录
    # if request.user.is_authenticated:
    #     print("已经登录了")
    #     if request.user.has_perm('front.change_article'):
    #         return HttpResponse("这是添加文章的页面")
    #     else:
    #         return HttpResponse("您没有权限访问",status=403)
    # else:
    #     return redirect(reverse('login'))
    return HttpResponse("判断是否有权限")


def operate_group(request):
    # group = Group.objects.create(name="运营")
    # content_type = ContentType.objects.get_for_model(Article)
    # permissions = Permission.objects.filter(content_type=content_type)
    # group.permissions.set(permissions)
    # group.save()
    # group = Group.objects.filter(name="运营").first()
    # user = User.objects.first()
    # user.groups.add(group)
    # user.save()
    #user = User.objects.first()
    # perssions = user.get_all_permissions() #获取用户所有的权限
    # #本来front_user_user_permissions 这里边 存放用户所有的权限
    # #但是我们现在 将用户添加到了运营组中 这个时候权限就是来自user_groups
    # #不再是 ront_user_user_permissions
    # print(perssions)
    # if user.has_perms(['front.view_article','front.add_article']):
    #     print("拥有该权限")
    # else:
    #     print("没有操作文章的权限")
    group = Group.objects.create(name="管理员")
    content_type = ContentType.objects.get_for_model(Article)
    permissions = Permission.objects.filter(content_type=content_type)
    group = Group.objects.filter(name="管理员").first()
    group.permissions.set(permissions)
    group.save()
    user = User.objects.filter(username='kangbazi').first()
    user.groups.add(group)
    return HttpResponse("操作分组")








